package com.channelsharing.cloud.aliyun.ocr;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

import com.channelsharing.common.utils.HttpUtils;
import com.channelsharing.common.yaml.YamlProperties;
import org.apache.commons.codec.binary.Base64;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.channelsharing.common.exception.SystemInnerBusinessException;
import com.channelsharing.common.utils.OkHttpClientUtil;

import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by liuhangjun on 2018/7/12.
 */
public final class IdCardRecognizeUtil {
    private static Logger logger = LoggerFactory.getLogger(IdCardRecognizeUtil.class);
    private static String APP_KEY = YamlProperties.getProperty("aliyun.ocr.appKey");
    private static String APP_SECRET = YamlProperties.getProperty("aliyun.ocr.appSecret");
    private static String APP_CODE = YamlProperties.getProperty("aliyun.ocr.appCode");
    private static String API_PATH = YamlProperties.getProperty("aliyun.ocr.apiPath");
    private static String API_HOST = YamlProperties.getProperty("aliyun.ocr.apiHost");


    private static final IdCardRecognizeUtil instance = new IdCardRecognizeUtil();


    public static JSONObject recognize(String fileUrl, String side) throws IOException {

        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + APP_CODE);
        //根据API的要求，定义相对应的Content-Type
        headers.put("Content-Type", "application/json; charset=UTF-8");
        Map<String, String> querys = new HashMap<String, String>();

        Request request = new Request.Builder().get().url(fileUrl).build();
        Response response = OkHttpClientUtil.execute(request);

        if (response.isSuccessful()) {
            byte[] fileContent = response.body().bytes();
            String base64 = Base64.encodeBase64String(fileContent);

            JSONObject configure = new JSONObject();
            configure.put("side", side);

            JSONObject body = new JSONObject();
            body.put("image", base64);
            body.put("configure", configure);
            String bodys = "{\"imgbase64\":\"" + base64 + "\"}";
            try {
                HttpResponse apiResponse = HttpUtils.doPost(API_HOST, API_PATH, "POST", headers, querys, bodys);
                if (apiResponse != null) {
                    JSONObject respBody = JSON.parseObject(EntityUtils.toString(apiResponse.getEntity()));
                    JSONObject data = respBody.getJSONObject("data");
                    if (data.get("side").equals("front")) {
return data.getJSONObject("front_side");
                    }else {
                        return data.getJSONObject("back_side");
                    }
                } else {
                    logger.error("request ocr idcard fail, fileUrl={}, side={}", fileUrl, side);
                    throw new SystemInnerBusinessException("身份证" + ("face".equals(side) ? "正" : "背") + "面识别失败，请重新拍摄");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        throw new SystemInnerBusinessException("文件下载失败");
    }

}
